package xyz.xtt.gateway.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.Base64;
import java.util.Objects;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@Slf4j
public class SHA256Utils {
	private static final String JOIN = "&";
	private static final String STR = "=";
	private static final String HMAC_SHA256 = "HmacSHA256";

	// 订单中心 OrderCenter 支付中心 PayCenter
	public static String sign(TreeMap<String, String> params, String secretKey) {
		StringBuilder sb = new StringBuilder();
		params.forEach((key, value) -> {
			sb.append(key).append(STR).append(value).append(JOIN);
		});
		// 在拼接好的字符串末尾加上Secret Key
		sb.append(secretKey);
		log.info("before sign:{}", sb.toString());
		byte[] hmac = hmacSha256(sb.toString().getBytes(), secretKey.getBytes());
		String signature = Base64.getEncoder().encodeToString(hmac);
		log.info("after sign:{}", signature);
		return signature;
	}

	private static byte[] hmacSha256(byte[] data, byte[] key) {
		try {
			Mac mac = Mac.getInstance(HMAC_SHA256);
			SecretKeySpec secretKeySpec = new SecretKeySpec(key, HMAC_SHA256);
			mac.init(secretKeySpec);
			return mac.doFinal(data);
		} catch (Exception e) {
			throw new RuntimeException("HmacSHA256 error: " + e.getMessage());
		}
	}

	public static boolean check(String target, String platform, String accessKey, String secretKey) {
		TreeMap<String, String> params = new TreeMap<>();
		params.put("platform", platform);
		params.put("accessKey", accessKey);
		String signature = sign(params, secretKey);
		return Objects.equals(signature, target);
	}

	public static boolean check(String target, String platform, String accessKey, String secretKey, String timestamp, String nonceStr) {
		TreeMap<String, String> params = new TreeMap<>();
		params.put("platform", platform);
		params.put("accessKey", accessKey);
		params.put("timestamp", timestamp);
		params.put("nonceStr", nonceStr);
		String signature = sign(params, secretKey);
		return Objects.equals(signature, target);
	}

}
